package com.example.application.service;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.application.bean.Info;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * author: fangjie email: syfangjie@live.cn date: 2021/1/3 11:14 上午
 */
public class InfoListener extends AnalysisEventListener<Info> {
  private static final Logger log = LoggerFactory.getLogger(InfoListener.class);

  private final static int BATCH_COUNT=1000;
  private final List<Info> list=new ArrayList<>(BATCH_COUNT);
  private final SqlService save;

  public InfoListener(){
    save=new SqlService();
  }


  @Override
  public void invoke(Info info, AnalysisContext analysisContext) {
    log.info("解析到一条数据:{}",info.toString());
    list.add(info);
    if(list.size()>=BATCH_COUNT){
      saveData();
      list.clear();
    }
  }

  @Override
  public void doAfterAllAnalysed(AnalysisContext analysisContext) {
    saveData();
    log.info("所有数据解析完成");
  }

  private void saveData(){
    save.save(list);
  }
}
